package com.ruoyi.web.test;

import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @Description:
 * @Author: zjy
 * @Date: 2024/4/26 0:31
 */
@Service
public class NotificationService {

    @Resource
    private TaskExecutor taskExecutor;

    /**
     * 具体执行任务
     * @param userId
     */
    @Async("taskExecutor")
    public void sendNotification(String userId) {

        // 获取并打印当前线程的ID
        long threadId = Thread.currentThread().getId();
        System.out.println("线程ID: " + threadId + " 正在发送通知给用户: " + userId);

        // 模拟发送通知的过程
        try {
            Thread.sleep(1000); // 模拟耗时操作
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IllegalStateException(e);
        }
        System.out.println("已通知用户: " + userId);
    }

    /**
     * 多线程批量发送通知
     * @param userIds 待发送通知的用户
     */
    public void sendNotificationsBatch(List<String> userIds) {
        List<CompletableFuture<Void>> futures = new ArrayList<>();

        for (String userId : userIds) {
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> sendNotification(userId), taskExecutor);
            futures.add(future);
        }

        // 等待所有任务完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        // 所有任务完成
        System.out.println("===任务全部完成!===");
    }
}
